package com.acegear.horizon.domain.repository;

import com.acegear.horizon.domain.models.Post;
import com.acegear.horizon.domain.repository.jpa.PostCommentRepository;
import com.acegear.horizon.domain.repository.jpa.UserPostRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * Created by wangsike on 2016/12/23.
 */
@Component
public class PostRepository {

    @Autowired
    private UserPostRepository userPostRepository;

    @Autowired
    private PostCommentRepository postCommentRepository;



    public Optional<Post> findByPostId(Long postId) {
        return userPostRepository.findByPostId(postId).map(Post::new);
    }


    public Stream<Post> findByUserId(Long userId, Pageable pageable) {
        return userPostRepository.findByUserIdAndDeletedOrderByIdDesc(userId, false, pageable)
                .stream()
                .map(Post::new);
    }

    public Integer countByUserId(Long userId) {
        return userPostRepository.countByUserIdAndDeleted(userId, false);
    }

    public Stream<Post> findCommentedPostByUserId(Long userId, Pageable pageable) {
        return postCommentRepository
                .findCommentedPostByUserId(userId, pageable)
                .stream()
                .map(postId -> findByPostId(postId).orElse(null))
                .filter(Objects::nonNull);
    }

    public Stream<Post> findAll() {
        return userPostRepository.findAll().stream().map(Post::new);
    }

    public Stream<Post> query(Long postId) {
        return userPostRepository.findByPostIdGreaterThan(postId).stream().map(Post::new);
    }
}
